import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import './router/before-each'
// ------- import通用组件 ------
import component from '@/components'
// ------- import ElementPlus start ------
import ElementPlus from 'element-plus'
// 配置中文
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
// ------ end ------
import Directives from '@/directives'
// ------- import vue-grid start ------
import VueGridLayout from 'vue-grid-layout'
// ------ end ------
import './assets/scss/index.scss'
import { getToken } from '@/utils/token'
import useMenuStore from '@/stores/menu-store'
import useLoginStore from '@/stores/login-store'
// ------- import date-format start ------
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')
// ------ date-format end ------
const app = createApp(App)
// 定义全局变量，需要配合 use-global.js 使用
app.config.globalProperties.$dayjs = dayjs
app.config.globalProperties.$http = import.meta.env.VITE_BASE_URL
app.config.globalProperties.$fileUrl = import.meta.env.VITE_BASE_URL_FILE

// 1.创建pinia,并挂载到app上
app.use(createPinia())

// 2.根据是否存在token,去获取动态路由信息，此法能解决页面刷新时，由于路由守卫先执行导致的空路由警告
const getMenuTreeByToken = async () => {
    if (getToken()) {
        if ( !useMenuStore()?.layoutMenuTree?.length) {
            await useLoginStore()?.getUserInfo()
            await useMenuStore()?.getUserMenuTree()
        }
    }
}
const call = async () => {
    // 3.先获取菜单树，再挂载路由（路由守卫）
    await getMenuTreeByToken()
    app.use(router).use(Directives).use(VueGridLayout).use(component)
    // 全局使用element-plus组件与图标
    app.use(ElementPlus, {locale: zhCn,})
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        app.component(key, component)
    }
    app.mount('#app')
}
// 4.调用挂载
call().then()

